#include "relationgadlg.h"
#include "ui_relationgadlg.h"
#include "tabledefine.h"
#include <QDebug>

extern QSqlDatabase projectDB;

RelationGADlg::RelationGADlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RelationGADlg)
{
    ui->setupUi(this);
    
    // Create and set the data model
    model = new QSqlQueryModel;
    model->setQuery(QString("select * from %1 where %2 = 13").arg(ADDRESS_TABLE_NAME, TYPE), projectDB);
    model->setHeaderData(1, Qt::Horizontal, "地址id");
    model->setHeaderData(2, Qt::Horizontal, "值");
    model->setHeaderData(3, Qt::Horizontal, "名称");
    model->setHeaderData(4, Qt::Horizontal, "描述");
    model->setHeaderData(5, Qt::Horizontal, "上级id");
    model->setHeaderData(6, Qt::Horizontal, "群组地址");
    model->setHeaderData(7, Qt::Horizontal, "产品id");
    model->setHeaderData(8, Qt::Horizontal, "设备id");
    model->setHeaderData(9, Qt::Horizontal, "eeprom地址");
    model->setHeaderData(10, Qt::Horizontal, "地址序号");
    model->setHeaderData(11, Qt::Horizontal, "类型");
    
    //Show data use tableView and set tableView
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置选中时选中一行
    ui->tableView->setModel(model);
    ui->tableView->hideColumn(0);  //隐藏id列(第0列)
    ui->tableView->hideColumn(1);
    ui->tableView->hideColumn(2);
    ui->tableView->hideColumn(5);
    ui->tableView->hideColumn(7);
    ui->tableView->hideColumn(8);
    ui->tableView->hideColumn(9);
    ui->tableView->hideColumn(10);
    ui->tableView->hideColumn(11);
    ui->tableView->resizeColumnsToContents();
    ui->tableView->verticalHeader()->hide();
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//均分列
    
    //connect
    connect(ui->cancelBtn, SIGNAL(clicked(bool)), this, SLOT(close()));
    connect(ui->OKBtn, SIGNAL(clicked(bool)), this, SLOT(getGAInfo()));
    connect(ui->OKBtn, SIGNAL(clicked(bool)), this, SLOT(accept()));
    connect(ui->tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(updateOKBtn()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(getGAInfo()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
}

RelationGADlg::~RelationGADlg()
{
    delete ui;
}

void RelationGADlg::updateOKBtn()
{
    ui->OKBtn->setEnabled(true);
}

void RelationGADlg::getGAInfo()
{
    int row = ui->tableView->currentIndex().row();  //获取当前行
    GA = model->data(model->index(row, 6)).toString();  //获取群组地址
}
